﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Windows.Forms;
using Command.Model;
using System.Collections;
using System.Data;
using System.IO;
using System.Globalization;

namespace NJGZBTYHXT
{
    public class FirstOption
    {
        private ArrayList list;
        XmlDocument xmlDoc;
        public XmlDocument XmlDoc
        {
            get { return xmlDoc; }
            set { xmlDoc = value; }
        }
        string filename;
        public string Filename
        {
            get { return filename; }
            set { filename = value; }
        }
        XmlNode root;
        private bool isopen;
        public XmlNode RootNode
        {
            get { return root; }
            set { root = value; }
        }

        public FirstOption()
        {
            list = new ArrayList();
            xmlDoc = new XmlDocument();
            filename = Application.StartupPath + "\\" + System.Configuration.ConfigurationManager.AppSettings["AlternateConfigFile"];
            xmlDoc.Load(filename);
            root = xmlDoc.SelectSingleNode("/Alternate");
            isopen = root.Attributes["open"].Value.ToUpper().Equals("TRUE") ? true : false;
        }

        internal bool IsOpen
        {
            get { return isopen; }
            set { isopen = value; }
        }

        internal XmlNodeList GetList()
        {
            return xmlDoc.SelectNodes("/Alternate/item");
        }

        internal int[] SelectData(DataGridView myDgv)
        {
            IList<DataGridViewRow> clist = new List<DataGridViewRow>();

            XmlNodeList xns = GetList();

            //循环数据源
            foreach (DataGridViewRow row in myDgv.Rows)
            {
                foreach (XmlNode xn in xns)
                {
                    int start = int.Parse(xn.Attributes["start"].Value);
                    int end = int.Parse(xn.Attributes["end"].Value);
                    string column = xn.Attributes["column"].Value;
                    string value = xn.Attributes["value"].Value;

                    bool isRead = false;

                    //检查候选设置
                    if (xn.Attributes["range"].Value.ToUpper().Equals("TRUE"))
                    {
                        int rvalue = Convert.ToInt32(row.Cells[column].Value);

                        if (rvalue >= start && rvalue <= end)
                        {
                            list.Add(xn);
                            isRead = true;
                        }
                    }
                    else
                    {
                        if (row.Cells[column].Value.Equals(value))
                        {
                            isRead = true;
                        }
                    }

                    //是否符合读取条件
                    if (isRead)
                    {
                        clist.Add(row);
                    }
                }
            }

            int[] indexs = new int[clist.Count];

            for (int i = 0; i < clist.Count; i++)
            {
                indexs[i] = clist[i].Index;
            }

            return indexs;
        }

        internal void Delete()
        {
            foreach (XmlNode xn in list)
            {
                xmlDoc.RemoveChild(xn);
            }
        }

        public static void OutExcel(DataGridView dgv, Form form)
        {
            try
            {
                if (dgv.Rows.Count > 0)
                {
                    SaveFileDialog sfd = new SaveFileDialog();

                    sfd.InitialDirectory = @"C:\program files\山西万鸿\农机购置补贴摇号系统\excel\";

                    sfd.RestoreDirectory = true;

                    sfd.Filter = "Microsoft Excel 97/2000/XP/2003 文件|*.xls|Microsoft Excel 文件|*.xlsx|WPS 表格|*.et|CSV (逗号分割)|*.csv";

                    if (sfd.ShowDialog(form) == DialogResult.OK)
                    {
                        string ext = Path.GetExtension(sfd.FileName);

                        string path = Path.GetDirectoryName(sfd.FileName);

                        string fileName = Path.GetFileNameWithoutExtension(sfd.FileName);

                        Common.Excel.NPOIHelper.ListColumnsName = new SortedList(new MyComparer());

                        foreach (DataGridViewColumn dgvc in dgv.Columns)
                        {
                            Common.Excel.NPOIHelper.ListColumnsName.Add(dgvc.Name, dgvc.Name);
                        }

                        Common.Excel.NPOIHelper.ExportExcel(Common.Excel.DataConvart.Dgv2Dt(dgv), path + "\\" + fileName + ext);

                        MessageBox.Show(fileName + " 文件保存成功。\n", "提示");
                    }
                }
                else
                {
                    MessageBox.Show("没有数据", "提示");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误");
            }
        }

        /// <summary>
        /// 导出Excel
        /// </summary>
        /// <param name="dgv"></param>
        /// <param name="savefile"></param>
        public static void OutExcel(DataGridView dgv, string savefile)
        {
            try
            {
                if (dgv.Rows.Count > 0)
                {
                    //string ext = Path.GetExtension(savefile);

                    //string path = Path.GetDirectoryName(savefile);

                    //string fileName = Path.GetFileNameWithoutExtension(savefile);

                    DataTable dt = Common.Excel.DataConvart.Dgv2Dt(dgv);

                    string[] cs = new string[] { 
                        "id", "市", "县", "乡镇", "村", "地址", "受益户身份", "手机号码", "姓名", "性别", "联系电话", "证件号码", "出生日期", "文化程度", 
                        "主要农作物", "耕地面积", "机具大类", "机具小类", "机具品目", "机具型号", "机具编号", "指标确认书编号", "数量", "特殊设备数量", 
                        "生产企业", "单台国补（元）", "国补总额（元）", "单台省补（元）", "省补总额（元）", "单台市补（元）", "单台县补（元）", "备注", 
                        "状态", "录入日期" };

                    Common.Excel.NPOIHelper.ListColumnsName = new SortedList(new MyComparer());

                    foreach (string csname in cs)
                    {
                        Common.Excel.NPOIHelper.ListColumnsName.Add(csname, csname);
                    }

                    //foreach (DataColumn csname in dt.Columns)
                    //{
                    //    Common.Excel.NPOIHelper.ListColumnsName.Add(csname.ColumnName, csname.ColumnName);
                    //}

                    Common.Excel.NPOIHelper.ExportExcel(dt, savefile);
                }
            }
            catch (Exception) { }
        }

        public static DataTable DataGridView2DataTable(DataGridView dataGridView1)
        {
            DataTable dt = new DataTable();

            foreach (DataGridViewColumn dgvc in dataGridView1.Columns)
            {
                dt.Columns.Add(dgvc.Name);
            }

            foreach (DataGridViewRow dgvr in dataGridView1.Rows)
            {
                object[] p = new object[dataGridView1.Columns.Count];
                for (int i = 0; i < dataGridView1.Columns.Count; i++)
                {
                    p[i] = dataGridView1.Columns[i].Name;
                }
                dt.Rows.Add(p);
            }

            return dt;
        }

        internal static DataGridViewRow SelectRow(DataGridView dgv, int index)
        {
            if (index > dgv.Rows.Count / 2)
            {
                for (int i = dgv.Rows.Count - 1; i >= 0; i--)
                {
                    if (dgv.Rows[i].Cells["ID"].Value.ToString() == index.ToString())
                    {
                        return dgv.Rows[i];
                    }
                }
            }
            else
            {
                foreach (DataGridViewRow row in dgv.Rows)
                {
                    if (row.Cells["ID"].Value.ToString() == index.ToString())
                    {
                        return row;
                    }
                }
            }
            return null;
        }

        /// <summary>
        /// 显示或隐藏列
        /// </summary>
        /// <param name="dataGridView1"></param>
        /// <param name="columnsStr"></param>
        /// <param name="isShow"></param>
        internal static void DataGridViewSHC(DataGridView dataGridView1, string columnsStr, bool isShow, bool isUpHeaderText)
        {
            if (columnsStr == "")
            {
                foreach (DataGridViewColumn coum in dataGridView1.Columns)
                {
                    coum.Visible = isShow;
                }
            }
            else
            {
                foreach (DataGridViewColumn coum in dataGridView1.Columns)
                {
                    coum.Visible = !isShow;
                }

                string[] columns = columnsStr.Split(',');

                foreach (string column in columns)
                {
                    if (dataGridView1.Columns.Contains(column))
                    {
                        dataGridView1.Columns[column].Visible = isShow;

                        if (isUpHeaderText)
                        {
                            if (column == "国补总额（元）") { DataGridViewUpdateColumnName(dataGridView1, column, "国补总额"); }
                            if (column == "省补总额（元）") { DataGridViewUpdateColumnName(dataGridView1, column, "省补总额"); }
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 更新列标题显示名
        /// </summary>
        /// <param name="dataGridView1"></param>
        /// <param name="columnName"></param>
        /// <param name="headerText"></param>
        internal static void DataGridViewUpdateColumnName(DataGridView dataGridView1, string columnName, string headerText)
        {
            if (dataGridView1.Columns.Contains(columnName))
            {
                dataGridView1.Columns[columnName].HeaderText = headerText;
            }
        }
    }

    /// <summary>
    /// 自定义排序规则
    /// </summary>
    class MyComparer : IComparer
    {
        public int Compare(object x, object y)
        {
            //不排序
            return -1;
        }
    }
}
